/** @(#)NonrevEncr.java    
 *
 * Project: TOPEPS
 *
 * Modify Information:
 * =============================================================================
 *   Author         Date          Description
 *   ------------ ---------- ---------------------------------------------------
 *   TOPEPS Team       2007-4-16       first release
 *   
 *   
 * Copyright Notice:
 * =============================================================================
 *       Copyright 2007 Huateng Software, Inc. All rights reserved.
 *
 *       This software is the confidential and proprietary information of
 *       Shanghai HUATENG Software Co., Ltd. ("Confidential Information").
 *       You shall not disclose such Confidential Information and shall use it
 *       only in accordance with the terms of the license agreement you entered
 *       into with Huateng.
 *
 * Warning:
 * =============================================================================
 * 
 */
package com.gopay.common.util;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;

//import com.gopay.common.cipher.utils.SensitiveInfoDictionaryUtils;

/**
 * 不可逆密钥类.
 * 
 * @author zhanglei - 2012-12-26
 */
public class NonrevEncr {

	protected NonrevEncr() {
		throw new UnsupportedOperationException();
	}

	public static final String sha1(String src) {
		final int i4 = 4;
		final int i0xf = 0xf;
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] strTemp = src.getBytes("utf-8");
			MessageDigest mdTemp = MessageDigest.getInstance("SHA-1");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			/* 转换为16进制 */
			int j = md.length;
			char[] str = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				// int aa = byte0 >>> i4;
				// int b = aa & i0xf;
				str[k++] = hexDigits[byte0 >>> i4 & i0xf];
				str[k++] = hexDigits[byte0 & i0xf];
			}
			return new String(str);
		} catch (UnsupportedEncodingException ueex) {
			throw new RuntimeException();
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 生成摘要（剩余信息保护版）
	 * fanghw 20161018
	 * @param src
	 * @return
	 */
	public static final String sha1(StringBuilder src) {
	    return sha(src, "SHA-1");
	}
	
	/**
     * SHA-512算法 返回密文长度为128
     * @param src
     * @return
     */
    public static final String sha512(StringBuilder src) {
        // 返回密文前面增加前缀 为哪种加密算法 方面后期维护
    	/**
         * add by zyt 	将用户密码或密保等更新为sha512的时候，存储sha512和sha1的结果集作为字典，
         * 				这样，在应急回滚的时候，可以采用与敏感字段回滚一样的方案。
         * 2017-1-19
         */
    	String sha512Src = "SHA512_"+sha(src, "SHA-512");
        saveDicPwd(src, sha512Src);
        return sha512Src;
    }
    
    public static final String sha(StringBuilder src, String encryptType) {
        final int i4 = 4;
        final int i0xf = 0xf;
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            char[] srcChars=new char[src.length()];
            src.getChars(0, srcChars.length, srcChars, 0);
            
            byte[] strTemp =getBytes(srcChars);
            MessageDigest mdTemp = MessageDigest.getInstance(encryptType);
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            /* 转换为16进制 */
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                // int aa = byte0 >>> i4;
                // int b = aa & i0xf;
                str[k++] = hexDigits[byte0 >>> i4 & i0xf];
                str[k++] = hexDigits[byte0 & i0xf];
            }
            return new String(str);
        }catch (Exception e) {
            return null;
        }
    }
    
	private static byte[] getBytes(char[] chars) {
	    Charset cs = Charset.forName ("UTF-8");
	    CharBuffer cb = CharBuffer.allocate (chars.length);
	    cb.put (chars);
	    cb.flip ();
	    ByteBuffer bb = cs.encode (cb);
	    byte[] tmpBArr=bb.array();
	    byte[] retArr=new byte[bb.limit()];
	    for(int i=0;i<bb.limit();i++){
	        retArr[i]=tmpBArr[i];
	    }
	    
	    return retArr;

	  }
	
	/**
     * 
     * @Description: 		将用户密码或密保等更新为sha512的时候，存储sha512和sha1的结果集作为字典，
     * 						这样，在应急回滚的时候，可以采用与敏感字段回滚一样的方案。 
     * @param pwd			原文
     * @param sha512Pwd 	sha512处理后的结果
     * @author zyt
     */
    private static void saveDicPwd(StringBuilder pwd, String sha512Pwd){
    	String sha1Pwd = sha1(pwd);
    	//SensitiveInfoDictionaryUtils.sendDiffShaPwd(sha512Pwd, sha1Pwd);
    }
	
	public static void main(String[] args){
	    String custId="0000037999";
	    String p="1111aaaa";
	    String pq="你的出生地？";
	    String pa="陆良";
	    
	    String plain="00000048171326901111aaaa";
	    String pwdDb="4015b089b2a7bd0032b0deb7c03984c822df0c36";
	    StringBuilder sbPlain=new StringBuilder(plain);
	    
	    String s1=NonrevEncr.sha1(sbPlain);
	    System.out.println(s1);
	    
	    String s2=NonrevEncr.sha1(plain);
        System.out.println(s2);
        
        String s3=NonrevEncr.sha512(sbPlain);
        System.out.println(s3);
	    
	    
	    System.out.println("end");
	    
	    
	}
}
